import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/item_qa_doctor.dart';
import 'package:qunaimedical/components/search_bar.dart';
import 'package:qunaimedical/models/qa_doctor.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/values/urls.dart';

class DoctorListPage extends StatefulWidget {
  const DoctorListPage({Key? key}) : super(key: key);

  @override
  State<DoctorListPage> createState() => _DoctorListPageState();
}

class _DoctorListPageState extends State<DoctorListPage> {
  TextEditingController _keywordController = TextEditingController();
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  /// 医生列表
  List<QADoctor> _items = [];
  List<QADoctor> _filteredData = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('医疗专家')),
      body: Column(
        children: [
          _buildSearchBar(),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullDown: true,
              enablePullUp: false,
              onRefresh: _fetchDoctorList,
              child: ListView.builder(
                itemBuilder: (c, i) => QAItemDoctor(_filteredData[i]),
                itemCount: _filteredData.length,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container _buildSearchBar() {
    return Container(
      color: Colors.white,
      child: SearchBar(
        hintText: '输入关键字搜索',
        controller: _keywordController,
        onSubmitted: (keyword) {
          late List<QADoctor> result;
          if (keyword.isNotEmpty) {
            result = _items
                .where((value) =>
                    value.name.contains(keyword) ||
                    value.phone.contains(keyword) ||
                    value.companyId.contains(keyword) ||
                    value.officeId.contains(keyword) ||
                    value.level.contains(keyword))
                .toList();
          } else {
            result = _items;
          }
          print(result);
          setState(() {
            _filteredData = result;
          });
        },
      ),
      padding: EdgeInsets.only(left: 16, top: 16, right: 16, bottom: 5),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _keywordController.dispose();
  }

  void _fetchDoctorList() async {
    try {
      Response response = await XHttp.instance.get(Urls.DOCTOR_LIST);
      if (mounted) {
        if (response.statusCode == 200 && response.data != null) {
          List list = response.data as List;
          List<QADoctor> data =
              List<QADoctor>.from(list.map((i) => QADoctor.fromJson(i)));
          if (mounted) {
            setState(() {
              _items.clear();
              _items.addAll(data);
              _filteredData.clear();
              _filteredData.addAll(data);
            });
          }
        }
      }
    } on DioError catch (e) {
      if (mounted) {
        CommonUtil.catchDioError(e);
      }
    } finally {
      _refreshController.refreshCompleted();
    }
  }
}
